package view


import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View

class ProgressBarView : View {
    companion object {
        private const val THINKNESS_P = 0.5f
        private const val MARGIN_COLOR = 0xffffbb33.toInt()
        private const val TEXT_COLOR = Color.BLACK
    }

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    private var with = 0f
    private var height = 0f
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val rectF = RectF()

    var currentValue = 0f
        set(value) {
            if (value != field) {
                field = value
                invalidate()
            }
        }

    var maxValue = 0f

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        with = w.toFloat()
        height = h.toFloat()
    }

    override fun onDraw(canvas: Canvas) {
        val x0 = with / 2
        val y0 = height / 2
        val a = if (width < height) with else height
        val r = a * 0.5f / (1 + 0.5f * THINKNESS_P)
        val d = r * THINKNESS_P

        paint.color = Color.GRAY
        paint.strokeWidth = d
        paint.style = Paint.Style.STROKE
        paint.strokeCap = Paint.Cap.ROUND
        canvas.drawCircle(x0, y0, r, paint)

        val max = maxValue

        paint.color = MARGIN_COLOR
        val angle = -(currentValue / max * 360)
        rectF.left = x0 - r
        rectF.top = y0 - r
        rectF.right = x0 + r
        rectF.bottom = y0 + r
        canvas.drawArc(rectF, -90f, angle, false, paint)

        textPaint.color = TEXT_COLOR
        textPaint.textSize = r * 0.5f
        textPaint.textAlign = Paint.Align.CENTER

        val measure = textPaint.fontMetrics
        val offset = (measure.top + measure.bottom) / 2

        val s = "${max.toInt() - currentValue.toInt()}s"
        canvas.drawText(s, x0, y0 - offset, textPaint)
    }
}

